import request from '@/utils/request'

export const aiApi = {
  // AI出题
  generateQuestion(data) {
    return request({
      url: '/api/ai/generate-question',
      method: 'post',
      data
    })
  },

  // AI对话
  chat(data) {
    return request({
      url: '/api/chat/chat',
      method: 'post',
      data
    })
  },

  // 获取用户出题历史
  getQuestionHistory(userId) {
    return request({
      url: '/api/ai/questions',
      method: 'get',
      params: { userId }
    })
  },

  // 获取用户对话历史
  getChatHistory(userId, sessionId) {
    return request({
      url: '/api/chat/chats',
      method: 'get',
      params: { userId, sessionId }
    })
  },

  // 答题总结分析
  summary(data) {
    return request({
      url: '/api/ai/summary',
      method: 'post',
      data
    })
  },

  // 获取会话列表
  getSessions(userId) {
    return request({
      url: '/api/chat/sessions',
      method: 'get',
      params: { userId }
    })
  },
  // 新建会话
  createSession(data) {
    return request({
      url: '/api/chat/sessions',
      method: 'post',
      data
    })
  },
  // 获取会话历史
  getHistory(userId, sessionId) {
    return request({
      url: '/api/chat/history',
      method: 'get',
      params: { userId, sessionId }
    })
  },
  // 保存/更新会话消息
  saveHistory(userId, sessionId, content, grade, knowledgePoint) {
    return request({
      url: '/api/chat/save',
      method: 'post',
      data: { userId, sessionId, content, grade, knowledgePoint }
    })
  },
  // 流式对话输出
  chatStream({ userId, sessionId, message }, onChunk, onEnd, onError) {
    fetch('/api/chat/chat-stream', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId, sessionId, message })
    }).then(async res => {
      const reader = res.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let done = false;
      while (!done) {
        const { value, done: readerDone } = await reader.read();
        if (value) {
          onChunk && onChunk(decoder.decode(value));
        }
        done = readerDone;
      }
      onEnd && onEnd();
    }).catch(err => {
      onError && onError(err);
    });
  },
  // 删除会话
  deleteSession(sessionId) {
    return request({
      url: '/api/chat/delete',
      method: 'delete',
      params: { sessionId }
    })
  },
  // guide-chat
  guideChat(messages) {
    return request({
      url: '/api/chat/guide-chat',
      method: 'post',
      data: { messages }
    })
  }
} 